<?php
namespace Home\Controller;

class UserController extends \Home\Controller\BaseController
{
	/**
	 * 用户登录
	 * @author 刘新
	 */
	public function login()
	{
		$param = I('params');
		$result = D('User')->login($param);
		$this->ajaxReturn($result);
	}
	
	/**
	 * 用户退出登录
	 * @author 刘新
	 */
	public function logout()
	{
		$param = I('params');
		$result = D('User')->logout($param);
		$this->ajaxReturn($result);
	}
	
	/**
	 * 用户注册
	 * @author 刘新
	 */
	public function register()
	{
		$param = I('params');
		$result = D('User')->addUser($param);
		$this->ajaxReturn($result);
	}
	
	/**
	 * 注册发送短信
	 * @author 刘新
	 */
	public function registerSms()
	{
		$this->sms();
	}
	
	/**
	 * 发送短信
	 * @author 刘新
	 */
	public function sms()
	{
		$param = I('params');
		//获取手机号并验证
		$mobile = $param['mobile'];
		$this->ajaxReturn($this->sendSms($mobile));
	}

	/**
	 * 修改支付密码
	 */
	public function changePayPwd(){
		$param = I('params');
		$oldPass = $param['oldPwd'];
		$newPass =$param['newPwd'];
		$loginPass = $param['loginPwd'];

		if(!$oldPass || !$newPass || !$loginPass) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		if($newPass == $oldPass) $this->ajaxReturn(array('error' => 1, 'info' => '新旧密码不能一样'));
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'trade_pwd');
		//查询成功
		if($res) {
			$oldPass =  \Common\Util\Util::encrypt($oldPass);
			if($res['trade_pwd'] === $oldPass) {
				$newPass = \Common\Util\Util::encrypt($newPass);
				$res = M('User')->where(array('id' => $this->user['userId']))->save(array('trade_pwd'=>$newPass));
				if($res) $this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
			} else {
				$this->ajaxReturn(array('error' => 1, 'info' => '原密码错误'));
			}
		}
		//更新失败
		if($res === false) $this->errorLog(__FILE__, __LINE__, M('User')->getDbError());
		$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
	}
	/**
	 * 同意认证接口
	 */
	public function consentCertification(){
 		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'authentication');
		//查询成功
		if($res['authentication']  == 0 ) {
			$res = M('User')->where(array('id' => $this->user['userId']))->save(array('authentication'=>'1'));
			if($res) $this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
		}
		//更新失败
		$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
	}
	/**
	 * 同意认证接口
	 */
	public function isCertification(){
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'authentication');
		//查询成功
		$detail = $this->returnOne('UserDetail', array('user_id' => $this->user['userId']), '', 'realname,social_no');
		$isdetail = $detail['social_no']?1:0;
		$this->ajaxReturn(array('error' => 0, 'authentication' => $res['authentication'],'detail'=>$isdetail));
		//更新失败

	}
	//获取群组信息
	public function getImgroup(){

		$iminfo = M("Imgroup")->select();
		$returninfo = array();
		foreach($iminfo as $key=>$val){
			$val['avatar_url'] = "http://114.215.209.229".$val['avatar_url'];
			$returninfo[$key] = $val;
		}
		$this->ajaxReturn(array('error' => 0, 'info' => $returninfo));
	}
	//获取用户信息
	public function getUserdata(){
		$param = I('params');
		$userids = explode(",",$param['userids']);
		$where['id'] = array("in",$userids);
		$iminfo = M("User")->where($where)->field(array("nickname","avatar_url","id"))->select();
		$returninfo = array();
		foreach($iminfo as $key=>$val){
			$val['avatar_url'] = "http://114.215.209.229".$val['avatar_url'];
			$returninfo[$key] = $val;
		}
		$this->ajaxReturn(array('error' => 0, 'info' => $returninfo));
	}
	/**
	 * 发送短信，内部调用
	 * @param string $mobile
	 * @author 刘新
	 */
	private function sendSms($mobile)
	{
		if(!preg_match('/^1\d{10}$/', $mobile)) return array('error' => 1, 'info' => '手机号格式错误');
		//查询
		$res = $this->returnOne('Sms', array('mobile' => $mobile), 'expire_time desc');
		
		if($res && $res['expire_time'] && $res['expire_time'] > time()) {
			$this->ajaxReturn(array('error' => 1, 'info' => '请勿重复点击'));
		}
		
		//生成随机字符串
		$rand = \Common\Util\Util::randStr();
		
		//查询短信最大保存时间
		$maxTime = global_config('sms_expire_time',true);
		$maxTime = intval($maxTime ? $maxTime : 10);
		//die(json_encode(array('error' => 1, 'info' => $maxTime)));
		//入库保存
		$data['mobile'] = $mobile;
		$data['code'] = $rand;
		$data['create_time'] = time();
		$data['expire_time'] = time() + $maxTime*60;
		$data['status'] = 1;
		$res = M('Sms')->add($data);
		if(!$res) return array('error' => 1, 'info' => '发送失败1');
		
		//调用短信平台发送
		$res = \Common\Util\Util::sms($mobile, $rand);
		if(!$res) return array('error' => 1, 'info' => '发送失败');
		return array('error' => 0, 'info' => '发送成功');
	}
	
	/**
	 * 设置密码
	 * @author 刘新
	 */
	public function setPassword()
	{
		$param = I('params');
		$oldPass = I('data.oldPwd', '', '/^\w{32,64}$/', $param);
		$newPass = I('data.newPwd', '', '/^\w{32,64}$/', $param);
		$sureNewPass = I('data.sureNewPwd', '', '/^\w{32,64}$/', $param);
		if(!$oldPass || !$newPass || !$sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		//判断两次新密码是否一致
		if($newPass !== $sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '两次密码不一致'));
		
		//查询旧密码
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'login_pwd');
		
		//查询成功
		if($res) {
			$oldPass =  \Common\Util\Util::encrypt($oldPass);
			if($res['login_pwd'] === $oldPass) {
				$newPass = \Common\Util\Util::encrypt($newPass);
				$res = M('User')->where(array('id' => $this->user['userId']))->save(array('login_pwd'=>$newPass));
				if($res) $this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
			} else {
				$this->ajaxReturn(array('error' => 1, 'info' => '原密码错误'));
			}
		}
		
		//更新失败
		if($res === false) $this->errorLog(__FILE__, __LINE__, M('User')->getDbError());
		$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
	}
	
	/**
	 * 设置密码
	 * @author 刘新
	 */
	public function setTradePassword()
	{
		$param = I('params');
		$loginPass = I('data.loginPass', '', '/^\w{32,64}$/', $param);
		$newPass = I('data.newPwd', '', '/^\w{32,64}$/', $param);
		$sureNewPass = I('data.sureNewPwd', '', '/^\w{32,64}$/', $param);
		if(!$loginPass || !$newPass || !$sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		//判断两次新密码是否一致
		if($newPass !== $sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '两次密码不一致'));
	
		//查询登录密码
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'login_pwd');
	
		//查询成功
		if($res) {
			$loginPass =  \Common\Util\Util::encrypt($loginPass);
			if($res['login_pwd'] === $loginPass) {
				$newPass = \Common\Util\Util::encrypt($newPass);
				$res = M('User')->where(array('id' => $this->user['userId']))->save(array('trade_pwd'=>$newPass));
				if($res) $this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
			} else {
				$this->ajaxReturn(array('error' => 1, 'info' => '登录密码错误'));
			}
		}
	
		//更新失败
		if($res === false) $this->errorLog(__FILE__, __LINE__, M('User')->getDbError());
		$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
	}
	
	/**
	 * 找回密码
	 * @author 刘新
	 */
	public function forgetPassword()
	{
		$param = I('params');
		$mobile = $param['mobile'];
		$code = $param['code'];
		$newPass = $param['loginPass'];
	
		//检验参数及判断两次新密码是否一致
//		if(!$mobile || !$newPass || !$code || !$sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
//		if($newPass !== $sureNewPass) $this->ajaxReturn(array('error' => 1, 'info' => '两次密码不一致'));
		
		//查询用户信息
		$return = array('error' => 1, 'info' => '重置密码失败');
		$res = $this->returnOne('User', array('mobile' => $mobile), '', 'login_pwd,id,pwd_err_count');
		
		//查询成功
		if($res) {
			//验证账号是否被锁定
//			$errorCount = global_config('pwd_err_count') ? global_config('pwd_err_count') : 3;
//			if($res['pwd_err_count'] >= $errorCount) $this->ajaxReturn(array('error' => 1, 'info' => '账号已被锁定'));
//
			//验证码校验
			$res = $this->returnOne('Sms', array('mobile' => $mobile, 'code' => $code));
			if($res) {
				//判断验证码是否过期
				$expireTime = time() + (global_config('sms_expire_time') ? global_config('sms_expire_time') : 5) * 60;
				if($expireTime < time()) $this->ajaxReturn(array('error' => 1, 'info' => '验证码过期'));

				//更新密码
				$newPass = \Common\Util\Util::encrypt($newPass);
				$res = M('User')->where(array('mobile' => $mobile))->save(array('login_pwd'=>$newPass));
					$user = M('User')->where(array('mobile' => $mobile))->find();
					$investinfo = M("Invest")->where(array("user_id"=>$user['id']))->select();
					$returninvest = array();
					if(is_array($investinfo)){
						foreach($investinfo as $key=>$val){
							if($val['status'] == '4'){
								$returninvest["receipt"] ++;
							}elseif($val['status'] == '5'){
								$returninvest["score"] ++;
							}elseif($val['status'] == '11'){
								$returninvest["refund"] ++;
							}
						}
					}
					$ut = M('UserToken')->where(array('user_id' => $user['id']))->order('expire_time desc')->field('id,user_token,status')->find();
					$result = array('userToken' => $ut['user_token'],
						'userId' => $user['id'],
						'expireTime' => $expireTime,
						'nickname'=>$user['nickname'],
						'username'=>$user['mobile'],
						"sex"=>$user['sex'],
						"liveAddress"=>$user['liveAddress'],
						"receipt"=>$returninvest['receipt'],
						"score"=>$returninvest['score'],
						"refund"=>$returninvest['refund'],
						"avatar_url"=>$user['avatar_url']?"http://114.215.209.229".$user['avatar_url']:""
					);

					$this->ajaxReturn(array('error' => 0, 'info' => $result));
			} else {
				$return['info'] = '验证码错误';
				$error = M('Sms')->getDbError();
			}
		} else {
			$return['info'] = '该用户不存在';
			$error = M('User')->getDbError();
		}
	
		//更新失败
		if($res === false) $this->errorLog(__FILE__, __LINE__, $error);
		$this->ajaxReturn($return);
	}



	/**
	 * 验证支付密码是否正确
	 */
	public function verificationTrade(){
		$param = I('params');
		$tradePwd = $param['tradePwd'];
		$res = $this->returnOne('User', array('id' => $this->user['userId']), '', 'trade_pwd');
		$tradePwd = \Common\Util\Util::encrypt($tradePwd);
		if($tradePwd == $res['trade_pwd']){
			$this->ajaxReturn(array('error' => 0,'info'=>array('is_trade' => 1)));
		}else{
			$this->ajaxReturn(array('error' => 1,'info'=>array( 'is_trade' => 0)));
		}
	}



	/**
	 * 支付回调接口
	 */
	public function nineteenPay(){
		$param = I('params');
		$retCode = $param['retCode'];
		$retDesc = $param['retDesc'];
		$orderSno = $param['orderSno'];
		$amount = $param['amount'];
		$Invest = M("Invest");
		$InvestInfo = $Invest->where(array("order_no"=>$orderSno))->find();
		if($InvestInfo){
			$Invest->where(array('order_no' => $orderSno))->save(array('paysuccess'=>'3'));
		}
	}

	/**
	 * 重置支付密码
	 *
	 */
	public function resetPaypass(){
		$param = I('params');
		$mobile = $param['mobile'];
		$veri_code = $param['veri_code'];
		$identification = $param['identification'];
		$pass = $param['pass'];
		$userId =  $this->user['userId'];
		if(!$userId) return array('error' => 1, 'info' => '参数错误');
		//判断电话、身份证是否为该用户所有
		$user = M("User")->where(array("id"=>$userId))->find();
		$user_mobile = $user['mobile'];
		if($mobile != $user_mobile){
			$this->ajaxReturn(array('error' => 1,'info'=>"此电话不是该用户所有"));
		}

		$userDetail = M("UserDetail")->where(array("user_id"=>$userId))->find();
		$user_social_no = $userDetail['social_no'];
		if($user_social_no != $identification){
			$this->ajaxReturn(array('error' => 1,'info'=>"身份证验证失败"));
		}
		//判断此验证码是否是该电话的
		$sms = M("Sms")->where(array("code"=>$veri_code,"mobile"=>$mobile))->find();
		if(empty($sms)){
			$this->ajaxReturn(array('error' => 1,'info'=>"验证码验证失败"));
		}
		//更新密码
		$newPass = \Common\Util\Util::encrypt($pass);
		$res = M('User')->where(array('id' => $this->user['userId']))->save(array('trade_pwd'=>$newPass));
		if($res){
			$this->ajaxReturn(array('error' => 0, 'info' => '更新成功'));
		}else{
			$this->ajaxReturn(array('error' => 1, 'info' => '更新失败'));
		}
	}
	/**
	 *获取用户收货地址
	 */
	public function receiptlist(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$res = M("Receipt")->where(array("user_id"=>$userId))->select();
		$this->ajaxReturn(array('error' => 0, 'info' => $res));
	}

	/**
	 *设置收货地址
	 */
	public function setreceipt(){
		$param = I('params');
		$userId =  $this->user['userId'];
		if(!$userId) return array('error' => 1, 'info' => '参数错误');
		$id = $param['id'];
		$data['province'] = $param['province'];
		$data['user_id'] = $userId;
		$data['isdefault'] = $param['isdefault'];
		if($param['isdefault'] == '1'){
			M("Receipt")->where(array("user_id"=>$userId))->save(array("isdefault"=>2));
		}
		$data['city'] = $param['city'];
		$data['area'] = $param['area'];
		$data['address'] = $param['address'];
		$data['phone'] = $param['phone'];
		$data['username'] = $param['username'];
		$data['create_time'] = date("Y-m-d H:i:s");
		if($id){
			$res = M("Receipt")->where(array("id"=>$id))->save($data);
		}else{
			$res = M("Receipt")->add($data);
		}
		if($res){
			$this->ajaxReturn(array('error' => 0, 'info' => '新建成功'));
		}else{
			$this->ajaxReturn(array('error' => 1, 'info' => '新建失败'));
		}
	}
	public function deletereceipt(){
		$param = I('params');
		$id = $param['id'];
		$res = M("Receipt")->where(array("id"=>$id))->delete();
		if($res){
			$this->ajaxReturn(array('error' => 0, 'info' => '删除成功'));
		}else{
			$this->ajaxReturn(array('error' => 1, 'info' => '新删除失败'));
		}
	}
	//获取默认接口
	public function defaultreceipt(){
		$param = I('params');
		$userId =  $this->user['userId'];
		if(!$userId) return array('error' => 1, 'info' => '参数错误');
		$res = M("Receipt")->where(array("user_id"=>$userId,"isdefault"=>'1'))->find();
		$this->ajaxReturn(array('error' => 0, 'info' => $res));
	}
	//修改默认接口
	public function changedefaulttreceipt(){
		$param = I('params');
		$userId =  $this->user['userId'];
		if(!$userId) return array('error' => 1, 'info' => '参数错误');
		$id = $param['id'];
		$res = M("Receipt")->where(array("user_id"=>$userId))->save(array("isdefault"=>2));
		$res = M("Receipt")->where(array("id"=>$id))->save(array("isdefault"=>1));
		$this->ajaxReturn(array('error' => 0, 'info' => '修改成功'));
	}
	//修改默认接口
	public function getreceiptbyid(){
		$param = I('params');
		$userId =  $this->user['userId'];
		if(!$userId) return array('error' => 1, 'info' => '参数错误');
		$id = $param['id'];
		$res = M("Receipt")->where(array("id"=>$id))->find();
		$this->ajaxReturn(array('error' => 0, 'info' => $res));
	}
	/**
	 *修改用户信息
	 */
	public function updateuserinfo(){
		$param = I('params');
		$userId =  $this->user['userId'];
		if(!$userId) return array('error' => 1, 'info' => '参数错误');
		$data = array();
		$param['sex']?$data['sex'] = $param['sex']:"";
		$param['province']?$data['province'] = $param['province']:"";
		$param['city']?$data['city'] = $param['city']:"";
		$param['area']?$data['area'] = $param['area']:"";
		$param['liveAddress']?$data['liveAddress'] = $param['liveAddress']:"";
		$param['nickname']?$data['nickname'] = $param['nickname']:"";
		$res = M("User")->where(array("id"=>$userId))->save($data);
		$this->ajaxReturn(array('error' => 0, 'info' => '修改成功'));
	}

	/**
	 * 获取优惠卷列表
	 */
	public function userCouponList(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$type = $param['type'];
		$where = array();
		$where['user_id'] = $userId;
		if($type==1){
			$where['express_time'] = array("lt",date("Y-m-d H:i:s"));
		}else{
			$where['express_time'] = array("gt",date("Y-m-d H:i:s"));
		}
		$userCouponinfo = M("UserCoupon")
			->join("LEFT JOIN mt_coupon on mt_user_coupon.coupon_id=mt_coupon.id")
			->where($where)
			->field("mt_user_coupon.*,mt_coupon.title,mt_coupon.full_type,mt_coupon.start_time,mt_coupon.end_time,mt_coupon.condition,mt_coupon.denomination")
			->select();
		$returninfo = array();
		foreach($userCouponinfo as $key=>$val){
			$returninfo[$key]['id'] = $val['id'];
			$returninfo[$key]['title'] = $val['title'];
			$returninfo[$key]['denomination'] = $val['denomination'];
			$returninfo[$key]['express_time'] = date("Y-m-d",strtotime($val['start_time']))."至".date("Y-m-d",strtotime($val['end_time']));
			$full_type = $val['full_type'];
			if($full_type == 1){
				$returninfo[$key]['sub_title'] = $val['condition']>0?"满".$val['condition']."可以用":"任意金额可以用";
			}elseif($full_type == 2){
				$returninfo[$key]['sub_title'] = $val['condition']>0?"满".$val['condition']."可以用打".$val['denomination']."%":"任意金额可以用";
			}elseif($full_type == 3){
				$returninfo[$key]['sub_title'] = "任意金额可以用";
			}
			$returninfo[$key]['status'] = $val['status'];//1 未使用 2 已经使用
		}
		$this->ajaxReturn(array('error' => 0, 'info' => $returninfo));
	}
	//兑换优惠卷
	public function exchangeCoupon(){
		$param = I('params');
		$userId =  $this->user['userId'];
		$couponcode = $param['couponcode'];
		$couponed = M("UserCoupon")->where(array("couponcode"=>$couponcode,"status"=>"1"))->find();
		if(empty($couponed)){
			$this->ajaxReturn(array('error' => 1, 'info' => "优惠卷不存在"));
		}
		M("UserCoupon")->where(array("couponcode"=>$couponcode))->save(array("user_id"=>$userId));
		$this->ajaxReturn(array('error' => 0, 'info' => "兑换成功"));
	}
}